import React                from 'react';
import {connect}            from 'react-redux';

import Nav                  from '../config/Navigator';
import Base                 from '../components/BaseComponent';
import config               from '../config';
import {Token}              from '../utils/Storage';
import {loadVip, loadAppId} from '../actions/common';

class Auth extends Base {

    _load(){
        var {appId} = Token.getInfo(), params = new Map(),
            {type, style} = this.props.match.params;
        config.set(style);
        if(!_.isEmpty(appId)){
            return this.props.loadVip().then(r => {
                var navParam, {userId, isAdmin} = r;
                if(!_.isEmpty(userId)){
                    Token.setInfo(Object.assign({appId}, r));
                    if(type === 'active'){
                        type = 'activeEdit';
                        navParam = userId;
                    }else if(isAdmin && type === 'shop'){
                        type = 'store';
                    }
                }else if(type !== 'cartList' && type !== 'shop'){
                    type = 'active';
                }
                this.router.replace(_.invoke(Nav, type, navParam));
            });
        }

        _.each(location.search.substring(1).split('&'), search => {
            var [key, val] = search.split('=');
            params.set(key, val);
        });

        this.props.loadAppId(params.get('code')).then((res) => {
            const {appId, avatar} = res
            if(!_.isEmpty(appId)){
                Token.setInfo({appId, avatar});
                return this._load();
            }
            this.alert('微信认证失败!');
        },()=>{
            this.alert('error')
        });

    }

    componentWillMount(){
        // localStorage.clear()
        // sessionStorage.clear()
        this._load();
    }

    render = () => null;
}

export default connect(undefined, {loadVip, loadAppId})(Auth);
